<template>
	<view class="container">
		<view class="top-padding"></view>
		<!-- 使用通用导航栏组件 -->
		<nav-bar title="卡包充值" />

		<uni-forms ref="form" :model="formData" :rules="rules">
			<uni-forms-item label="卡包名称" name="name" required>
				<uni-easyinput v-model="formData.name" placeholder="请输入卡包名称" />
			</uni-forms-item>

			<!-- 编辑默认卡包时不显示卡包类型 -->
			<uni-forms-item v-if="!isDefaultCardPackage" label="卡包类型" name="card_type" required>
				<uni-group>
					<view class="card-type-container">
						<view v-for="type in cardTypes" :key="type.value" class="card-type-item"
							:class="{ selected: formData.card_type === type.value }"
							@click="formData.card_type = type.value">
							<text>{{ type.text }}</text>
							<uni-icons :type="formData.card_type === type.value ? 'checkbox-filled' : 'checkbox'"
								:color="formData.card_type === type.value ? '#4cd964' : '#999'" size="20" />
						</view>
					</view>
				</uni-group>
			</uni-forms-item>

			<!-- 非次卡时显示充值金额、赠送金额和总金额 -->
			<uni-forms-item label="充值金额" name="recharge_amount" required>
				<uni-easyinput v-model="formData.recharge_amount" type="number" placeholder="请输入充值金额"
					@input="updateTotalAmount" />
			</uni-forms-item>
			<template v-if="formData.card_type !== 'per_use'">
				<uni-forms-item label="赠送金额" name="gift_amount" required>
					<uni-easyinput v-model="formData.gift_amount" type="number" placeholder="请输入赠送金额"
						@input="updateTotalAmount" />
				</uni-forms-item>

				<uni-forms-item label="总金额" name="total_amount">
					<uni-easyinput :value="computedTotalAmount" type="number" placeholder="自动计算" disabled />
				</uni-forms-item>
			</template>

			<!-- 次卡时直接显示总次数 -->
			<template v-else>
				<uni-forms-item label="总次数" name="total_amount" required>
					<uni-easyinput v-model="formData.total_amount" type="number" placeholder="请输入总次数" />
				</uni-forms-item>
			</template>
			<!-- 非次卡时显示几折卡 -->
			<template v-if="formData.card_type !== 'per_use'">
				<uni-forms-item label="客户打折" name="discount_rate" required>
					<view style="display: flex; align-items: center;">
						<uni-easyinput v-model="formData.discount_rate" type="number" placeholder="请输入客户打折(1-10)"
							style="flex: 1;" />
						<text style="margin-left: 10rpx;">折</text>
					</view>
				</uni-forms-item>
			</template>
			<!-- 添加员工选择 -->
			<uni-forms-item label="销售员" name="staff_id" required>
				<view class="staff-container">
					<view v-for="staff in staffList" :key="staff.user_id" class="staff-item"
						:class="{ selected: formData.staff_id === staff.user_id }" @click="selectStaff(staff)">
						<text class="staff-name">{{ staff.name }}</text>
						<uni-icons :type="formData.staff_id === staff.user_id ? 'checkbox-filled' : 'checkbox'"
							:color="formData.staff_id === staff.user_id ? '#4cd964' : '#999'" size="20" />
					</view>
				</view>
			</uni-forms-item>
			<button type="primary" @click="submitForm">保存</button>
		</uni-forms>
	</view>
</template>

<script>
import NavBar from '@/components/nav-bar/nav-bar.vue';
import cardPackage from '@/utils/card_package.js';
import Util from '@/utils/util.js';
import store from '@/utils/store.js'

export default {
	components: {
		NavBar
	},
	data() {
		return {
			staffList: [], // 添加员工列表初始化
			user_id: '',
			store_id: '',
			package_id: '',
			staff_id: '',
			formData: {
				package_id: '', // 卡包ID
				name: '', // 卡包名称
				card_type: 'comprehensive', // 卡包类型(综合卡/次卡)
				recharge_amount: '', // 充值金额(用户实际支付的金额)
				gift_amount: '', // 赠送金额(商家额外赠送的金额)
				total_amount: '', // 总金额(充值金额+赠送金额)
				discount_rate: 0, // 客户销售比例(百分比)
				store_id: '', // 所属店铺ID
				user_id: '', // 用户ID
				staff_id: '' // 销售员ID
			},
			cardTypes: [{
				value: 'default',
				text: '默认卡'
			},],
			rules: {
				name: {
					rules: [{
						required: true,
						errorMessage: '请输入卡包名称'
					}]
				},
				recharge_amount: {
					rules: [{
						required: true,
						errorMessage: '请输入充值金额',
						validateFunction: (rule, value, data, callback) => {
							return new Promise((resolve, reject) => {
								const num = Number(value);
								if (isNaN(num)) {
									reject('请输入有效数字');
								} else {
									resolve();
								}
							});
						}
					}]
				},
				card_type: {
					rules: [{
						required: true,
						errorMessage: '请选择卡包类型'
					}]
				},
				staff_id: {
					rules: [{
						required: true,
						errorMessage: '请选择销售员'
					}]
				},
				discount_rate: {
					rules: [{
						required: true,
						errorMessage: '请输入客户打折',
						validateFunction: (rule, value, data, callback) => {
							return new Promise((resolve, reject) => {
								const num = Number(value);
								if (isNaN(num)) {
									reject('请输入有效数字');
								} else if (num < 1 || num > 10) {
									reject('打折必须在1-10之间');
								} else if (!/^\d+(\.\d{0,1})?$/.test(value)) {
									reject('最多只能有一位小数');
								} else {
									resolve();
								}
							});
						}
					}]
				}
			}
		};
	},
	onLoad(options) {
		this.store_id = options.store_id || '';
		this.user_package_id = options.user_package_id || '';
		this.user_id = options.user_id || '';
		this.loadCardPackage(options.package_id);
		this.loadStaffList(this.store_id);
	},
	computed: {

		isDefaultCardPackage() {
			return this.formData.package_id && this.formData.card_type === 'default';
		},
		computedTotalAmount() {
			if (this.formData.card_type !== 'per_use') {
				const recharge = Number(this.formData.recharge_amount) || 0;
				const gift = Number(this.formData.gift_amount) || 0;
				return (recharge + gift).toFixed(2);
			}
			return this.formData.total_amount;
		}
	},
	methods: {
		selectStaff(staff) {
			this.formData.staff_id = staff.user_id;
		},
		async loadStaffList(storeId) {
			// 获取员工列表
			const staffResponse = await store.getStoreUsers(storeId, {
				'roles[]': ['staff', 'owner', 'manager'] // 修改为数组格式
			});
			this.staffList = staffResponse.list || []; // 修正数据结构访问
		},
		updateTotalAmount() {
			this.formData.total_amount = this.computedTotalAmount;
		},
		async submitForm() {
			try {
				// 检查负向充值时的赠送金额
				const rechargeAmount = Number(this.formData.recharge_amount);
				const giftAmount = Number(this.formData.gift_amount);
				if (rechargeAmount < 0 && giftAmount > 0) {
					uni.showToast({
						title: '负向充值时赠送金额只能填0',
						icon: 'none'
					});
					return;
				}
				// 根据卡包类型动态设置验证规则
				this.rules.total_amount = {
					rules: [{
						required: true,
						errorMessage: '请输入总金额'
					}]
				};
				// 确保总金额正确计算
				this.formData.total_amount = this.computedTotalAmount;
				this.rules.discount_rate = {
					rules: [{
						required: true,
						errorMessage: '请输入客户打折',
						validateFunction: (rule, value, data, callback) => {
							return new Promise((resolve, reject) => {
								const num = Number(value);
								if (isNaN(num)) {
									reject('请输入有效数字');
								} else if (num < 0 || num > 100) {
									reject('打折必须在0-100之间');
								} else {
									resolve();
								}
							});
						}
					}]
				};
				await this.$refs.form.validate();

				const params = {
					...this.formData,
					discount_rate: Number((this.formData.discount_rate / 10).toFixed(2)), // 转换为两位小数的数字类型
					gift_amount: Number(this.formData.gift_amount),
					recharge_amount: Number(this.formData.recharge_amount),
					total_amount: Number(this.formData.total_amount),
					user_id: this.user_id,
					store_id: this.store_id,
					package_id: this.user_package_id
				};
				console.log("--------", params);
				await cardPackage.recharge(params);
				uni.showToast({
					title: '充值成功',
					icon: 'success'
				});
				uni.$emit('refreshCardPackageList');
				uni.navigateBack();
			} catch (error) {
				uni.showToast({
					title: error.message || '保存失败',
					icon: 'none'
				});
			}
		},
		// 加载卡包数据时转换小数到百分比
		async loadCardPackage(packageId) {
			try {
				const res = await cardPackage.getById(packageId);
				this.formData = {
					...res,
					discount_rate: (res.discount_rate * 10).toFixed(1) // 转换为一位小数
				};
			} catch (error) {
				console.error(error);
				uni.showToast({
					title: '加载卡包信息失败',
					icon: 'none'
				});
			}
		}
	}
}
</script>

<style>
.container {
	padding: 0 30rpx;
	background-color: #f5f5f5;
}

uni-forms {
	margin: 0 -30rpx;
	padding: 20rpx 30rpx;
	background-color: #fff;
}

/* 添加以下样式 */
.card-type-container {
	display: flex;
	flex-wrap: wrap;
	gap: 10rpx;
	margin: 0 -10rpx;
}

.card-type-item {
	display: flex;
	align-items: center;
	padding: 15rpx 20rpx;
	border: 1rpx solid #ddd;
	border-radius: 10rpx;
	margin-right: 15rpx;
	margin-bottom: 15rpx;
	background-color: #fff;
}

.card-type-item.selected {
	background-color: #4cd964;
	border-color: #4cd964;
	color: white;
}

.card-type-item.selected .uni-icons {
	color: white;
	border: 1rpx solid white;
	border-radius: 50%;
}

.staff-container {
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 15rpx;
	padding: 10rpx;
}

.staff-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 15rpx;
	border: 1rpx solid #ddd;
	border-radius: 10rpx;
	background-color: #fff;
}

.staff-item.selected {
	background-color: #4cd964;
	border-color: #4cd964;
	color: white;
}

.staff-name {
	font-size: 28rpx;
	font-weight: bold;
	margin-bottom: 8rpx;
}

.staff-role {
	font-size: 24rpx;
	color: #666;
}

.staff-item.selected .staff-role {
	color: white;
}
</style>